app.directive("messages", ['messageServices', function(messageServices){
    return {
        restrict: 'EA',
		templateUrl: "app/shared/directives/admin/messages.view.html",
        link: function(scope, element, attrs){
            
			scope.messages = undefined;
			
			/**
			* Get all messages for the current user
			*
			* @param user user This is the targeted user
			*/
			scope.getMessagesCommand = function(user) {
				try {
					if(user == '' || user == undefined) {
						throw 'L\'utilisateur doit être renseigné';
					}
				
					scope.messagesLoading = true;
					messageServices.getMessages (function (data) {
						console.debug('messageServices get messages received');
						if(data.isFailed) {
							toastr.warning(data.exception, "Messages");
						}
						else {
							scope.messages = data.response;
						}
						scope.messagesLoading = false;
					}, user);
				}
				catch(exception) {
					toastr.error(exception, "Messages");
				}
			}	
			
			/**
			* Delete the targeted message
			*
			* @param message message This is the targeted message to delete
			*/
			scope.deleteMessageCommand = function(message) {
				try {
					if(message == '' || message == undefined) {
						throw 'Le message doit être renseigné';
					}
				
					scope.messagesLoading = true;
					messageServices.deleteMessage (function (data) {
						console.debug('messageServices delete message received');
						if(data.isFailed) {
							toastr.warning(data.exception, "Messages");
						}
						else {
							scope.messages.splice(1, 0, data.response);
						}
						scope.messagesLoading = false;
					}, message);
				}
				catch(exception) {
					toastr.error(exception, "Messages");
				}
			}
			
			/**
			* Send the message to another user
			*
			* @param user to This is the targeted user
			* @param string subject This is the subject message 
			* @param string message This is the main message
			*/
			scope.sendMessageCommand = function(to, subject, message) {
				try {
					if(to == '' || to == undefined) {
						throw 'Le destinataire doit être renseigné';
					}
					
					if(subject == '' || subject == undefined) {
						throw 'Le titre doit être renseigné';
					}
					
					if(message == '' || message == undefined) {
						throw 'Le message doit être renseigné';
					}
				
					scope.sendingMessage = true;
					messageServices.sendMessage (function (data) {
						console.debug('messageServices send message received');
						if(data.isFailed) {
							toastr.warning(data.exception, "Messages");
						}
						else {
							scope.messages.push(data.response);
						}
						scope.sendingMessage = false;
					}, to, subject, message);
				}
				catch(exception) {
					toastr.error(exception, "Messages");
				}
			}
        }
    };
}]);